package com.qdhh.enrollment.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;

@Component
public class JwtUtils {

    private static final String SECRET = "new-student-enrollment-system-secret-key-256-bit-value";
    private static final Key KEY = Keys.hmacShaKeyFor(SECRET.getBytes(StandardCharsets.UTF_8));
    private static final Duration EXPIRES_IN = Duration.ofDays(7);

    public String generateToken(String userId, String role) {
        Instant now = Instant.now();
        return Jwts.builder()
            .setSubject(userId)
            .claim("role", role)
            .setIssuedAt(Date.from(now))
            .setExpiration(Date.from(now.plus(EXPIRES_IN)))
            .signWith(KEY, SignatureAlgorithm.HS256)
            .compact();
    }

    public Claims parseToken(String token) {
        try {
            return Jwts.parserBuilder()
                .setSigningKey(KEY)
                .build()
                .parseClaimsJws(token)
                .getBody();
        } catch (Exception ex) {
            throw new AuthException("UNAUTHORIZED", ex);
        }
    }
}
